package com.ncepu.oj_new.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.ncepu.oj_new.judge.codesandbox.model.JudgeInfo;
import com.ncepu.oj_new.model.dto.question.JudgeCase;
import com.ncepu.oj_new.model.dto.question.JudgeConfig;
import com.ncepu.oj_new.model.entity.Question;
import com.ncepu.oj_new.model.enums.JudgeInfoMessageEnum;

import java.util.List;

/**
 * @author simon_jiang
 * @version 1.0
 */
public class JavaLanguageJudgeStrategy implements JudgeStrategy {

    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        Long memory = judgeInfo.getMemory();
        Long time = judgeInfo.getTime();

        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        Question question = judgeContext.getQuestion();

        JudgeInfo response = new JudgeInfo();
        response.setMemory(memory);
        response.setTime(time);
        // 判断沙箱执行的结果输出数量是否和与其输出数量一致
        if(inputList.size() != outputList.size()) {
            response.setMessage(JudgeInfoMessageEnum.WRONG_ANSWER.getText());
            return response;
        }
        // 以此判断每一项输出和与其输出是否相等
        for (int i = 0; i < judgeCaseList.size(); i++) {
            JudgeCase judgeCase = judgeCaseList.get(i);
            if(judgeCase.getOutput().equals(outputList.get(i))) {
                response.setMessage(JudgeInfoMessageEnum.WRONG_ANSWER.getText());
                return response;
            }
        }
        // 判断题目限制
        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        Long memoryLimit = judgeConfig.getMemoryLimit();
        Long timeLimit = judgeConfig.getTimeLimit();
        if (memory > memoryLimit) {
            response.setMessage(JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED.getValue());
            return response;
        }
        // Java 程序本身需要额外执行 10 秒钟
        long JAVA_PROGRAM_TIME_COST = 10000L;
        if (time - JAVA_PROGRAM_TIME_COST > timeLimit) {
            response.setMessage(JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED.getValue());
            return response;
        }
        response.setMessage(JudgeInfoMessageEnum.ACCEPTED.getValue());
        return response;

    }
}
